import numpy as np
import matplotlib.pyplot as plt

# 中文和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def differential_approximation_examples():
    """微分近似计算的实际例子"""
    
    examples = [
        {
            'name': '√9.01',
            'func': lambda x: np.sqrt(x),
            'deriv': lambda x: 1/(2*np.sqrt(x)),
            'x0': 9,
            'dx': 0.01,
            'exact': np.sqrt(9.01)
        },
        {
            'name': '2.002⁵',
            'func': lambda x: x**5,
            'deriv': lambda x: 5*x**4,
            'x0': 2,
            'dx': 0.002,
            'exact': 2.002**5
        },
        {
            'name': 'sin(0.1)',
            'func': np.sin,
            'deriv': np.cos,
            'x0': 0,
            'dx': 0.1,
            'exact': np.sin(0.1)
        },
        {
            'name': 'e^0.05',
            'func': np.exp,
            'deriv': np.exp,
            'x0': 0,
            'dx': 0.05,
            'exact': np.exp(0.05)
        }
    ]
    
    print("微分近似计算应用")
    print("=" * 60)
    
    for example in examples:
        approx = example['func'](example['x0']) + example['deriv'](example['x0']) * example['dx']
        error = abs(example['exact'] - approx)
        relative_error = error / abs(example['exact']) * 100
        
        print(f"\n{example['name']}:")
        print(f"  精确值: {example['exact']:.8f}")
        print(f"  近似值: {approx:.8f}")
        print(f"  绝对误差: {error:.10f}")
        print(f"  相对误差: {relative_error:.6f}%")
    
    # 可视化近似效果
    plt.figure(figsize=(10, 6))
    
    # 以√x为例展示近似效果
    x_vals = np.linspace(8, 10, 100)
    y_exact = np.sqrt(x_vals)
    y_approx = np.sqrt(9) + (1/(2*np.sqrt(9))) * (x_vals - 9)
    
    plt.plot(x_vals, y_exact, 'b-', linewidth=2, label='精确值: √x')
    plt.plot(x_vals, y_approx, 'r--', linewidth=2, label='线性近似')
    plt.scatter([9.01], [np.sqrt(9.01)], color='green', s=100, zorder=5)
    
    plt.annotate('近似点 (9.01, 3.001667)', (9.01, np.sqrt(9.01)), 
                xytext=(9.2, 3.1))
    plt.title('微分近似计算: √9.01 的线性近似')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.show()

differential_approximation_examples()